package org.high5.dataprovider;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class MyService extends IntentService implements LocationListener{
	private Intent intent;
	
	public MyService() {
		super("MyService");
		// TODO Auto-generated constructor stub
	}

	
	private LocationManager locationManager;

	private String provider;
	public static boolean working=true;
	private int seconds = 3;
	
	
	private void chechUserPrefs(){
		// open the DB
    	MyDBAdapter db = new MyDBAdapter(getApplicationContext());
    	db.open();
    	Cursor query = db.getUserPrefs();
    	Log.i("ChechPrefs","query ok");
    	if (query.moveToFirst()){
    		Log.i("CheckPrefs","Seconds: "+query.getString(1));
    		Log.i("CheckPrefs","Working: "+String.valueOf((int)Float.parseFloat(query.getString(2))==0));
    		seconds = (int)Float.parseFloat(query.getString(1));
    		if ((int)Float.parseFloat(query.getString(2))==0){
    			working=false;
    		}
    	}
    	db.close();
		
	}


	@Override
	public void onLocationChanged(Location location) {
		double lat =  location.getLatitude();
	    double lng =  location.getLongitude();
	    double alt =  location.getAltitude();
	    double acc =  location.getAccuracy();
	    Log.d("MyService","Latitude: "+String.valueOf(lat));
	    Log.d("MyService","Longitude: "+String.valueOf(lng));
	    Log.d("MyService","Altitude: "+String.valueOf(alt));
	    Log.d("MyService","Accurcy: "+String.valueOf(acc));
	}

	@Override
	public void onProviderDisabled(String provider) {
		Log.d("MyService","Provider disabled");
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		Log.d("MyService","Provider enebled");
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	


	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		this.intent = intent;
		
    	// open the DB
    	
    	
    	//get location manager
    	LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
		boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);

		/** Check if enabled and if not send user to the GSP settings **/
		/** Better solution would be to display a dialog and suggesting to  **/
		/** go to the settings **/
	
		while (working){
			MyDBAdapter db = new MyDBAdapter(getApplicationContext());
	    	db.open();
		
		if (!enabled) {
			// display the settings to turn the gps on
			// import android.provider.Settings;
		  Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		  startActivity(myIntent);
		}
		
		/** Get the location manager **/
	    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	    
	    
	    /** Define the criteria how to select the location provider -> use 
	     ** default **/
	    Criteria criteria = new Criteria();
	    provider = locationManager.getBestProvider(criteria, false);

	    Location location = locationManager.getLastKnownLocation(provider);

	    /** Initialize the location fields **/
	    if (location != null) {
	      Log.d("MyService","Provider " + provider + " has been selected.");
	      onLocationChanged(location);
	    } else {
	      Log.d("MyService","Location not available");
	    }
    	
    	
    	
    	
    		
    		
    		
    		try {
    			Log.d("MyService", "In loop");
    			Thread.sleep(seconds*1000);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		
    		String lat =  String.format("%f",(float)location.getLatitude());
    	    String lng =  String.format("%f",(float)location.getLongitude());
    	    String alt =  String.format("%f",(float)location.getAltitude());
    	    String acc =  String.format("%f",(float)location.getAccuracy());
    	    long unixTime = System.currentTimeMillis()/1000L;
    		db.insertLocation(lng,lat, unixTime, alt, acc);
    		db.close();
    		chechUserPrefs();
    		
    		
		}
		
	}
	
	
	
	@Override
	public void onDestroy(){
		if (working){
			
			onHandleIntent(intent);
					
			
		}
		else{
			working = true;
		}
	}




}
